package karileet.meeting.profile;

import karileet.meeting.profile.provider.WidgetProvider;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.media.AudioManager;
import android.util.Log;
import android.widget.RemoteViews;

/**
 * Class for enabling/disabling app
 * 
 * @author markus karileet
 */
public class MeetingProfile {
	private Context ctx;
	private ProfileConf state;
	private UserConf uc;
	private ProfileNotifications notification;
	
	public MeetingProfile(Context ctx) {
		this.ctx = ctx;
		state = new ProfileConf(ctx);
		uc = new UserConf(ctx);
		notification = new ProfileNotifications(ctx);
	}

	/**
	 * Method enables app and stores user current configuration
	 * @param storeState TODO
	 */
	public void enable(boolean storeState) {
		//store state when needed (after boot completed, do not store state,
		//because state is vibrate or silent anyway)
		Log.d(ProfileConf.APP, "Enabling profile");
		if (storeState) {
			uc.save();
		}
		if (state.isVibrateEnabled()) {
			uc.set(AudioManager.RINGER_MODE_VIBRATE);
		} else {
			uc.set(AudioManager.RINGER_MODE_SILENT);
		}
		notification.initiateNotification();
		state.setProfileEnabled(true);
	}

	/**
	 * Method disables app, restoring user previous configuration
	 */
	public void disable() {
		Log.d(ProfileConf.APP, "Disabling profile");
		int mode = uc.read();
		uc.set(mode);
		notification.cancelNotification();
		state.setProfileEnabled(false);
	}
	
	/**
	 * Method updates profile state (enable/disable vibrator) when
	 * profile is "on"
	 */
	public void update() {
		Log.d(ProfileConf.APP, "Updating vibrate conf");
		if (state.isProfileEnabled()) {
			if (state.isVibrateEnabled()) {
				uc.set(AudioManager.RINGER_MODE_VIBRATE);
			} else {
				uc.set(AudioManager.RINGER_MODE_SILENT);
			}
		}
	}
	
	/**
	 * Method updates widget button to show enabled or disabled image
	 */
	public void updateWidget() {
		int graphic = R.drawable.appwidget_dark_bg;
		if (state.isProfileEnabled()) {
			graphic = R.drawable.appwidget_dark_bg_focused;
		}
		RemoteViews views = new RemoteViews(ctx.getPackageName(), R.layout.widget);
		views.setImageViewResource(R.id.button1, graphic);
		AppWidgetManager manager = AppWidgetManager.getInstance(ctx);
		ComponentName cn = new ComponentName(ctx, WidgetProvider.class);
		manager.updateAppWidget(manager.getAppWidgetIds(cn), views);
	}
}
